package com.bupt.ilink.controller;

import com.bupt.ilink.entity.CosyVoiceRequest;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;

import java.nio.ByteBuffer;
import java.util.UUID;

@RestController
@RequestMapping("/dashscope")
public class DashScopeController {
    @Autowired
    private OssService ossService;
    @PostMapping("/cosyvoice")
    public R CosyVoice(@RequestBody CosyVoiceRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user =  (User) authentication.getPrincipal();
        String userId= user.getUserId();
        SpeechSynthesisParam param =
                SpeechSynthesisParam.builder()
                        .apiKey(request.getApiKey())
                        .model(request.getModel())
                        .voice(request.getVoice())
                        .build();
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
        ByteBuffer audio = synthesizer.call(request.getPrompt());
        byte[] audioBytes = audio.array();
        String filePath="multimodal/"+userId+"/";
        String fileName= UUID.randomUUID() + ".mp3";
        ossService.uploadFile(audioBytes, filePath, fileName);
        return R.ok("", ossService.getFileUrl(filePath+fileName));
    }
}
